package org.ctstudio.oa.duty.web;

import org.ctstudio.common.security.digest.DigestAlgorithm;
import org.ctstudio.oa.duty.bean.PwdEditBean;
import org.ctstudio.oa.duty.bean.Staff;
import org.ctstudio.oa.duty.dao.StaffMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ValidationUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@RequestMapping("/user")
public class UserController extends AbstractController {

  @Autowired
  private StaffMapper mapper;

  @RequestMapping(value = "/editPwd.do", method = RequestMethod.GET)
  public String beforeEditPasswrod(Model model) {
    PwdEditBean bean = new PwdEditBean();
    model.addAttribute("bean", bean);
    return "user/editPwd";
  }

  @RequestMapping(value = "/editPwd.do", method = RequestMethod.POST)
  public String onEditPasswrod(@ModelAttribute("bean") PwdEditBean bean, BindingResult result, HttpServletRequest request, Model model) {
    String logedUid = request.getRemoteUser();
    ValidationUtils.rejectIfEmptyOrWhitespace(result, "oldPwd", "CANNOTEMPTY");
    ValidationUtils.rejectIfEmptyOrWhitespace(result, "newPwd", "CANNOTEMPTY");
    ValidationUtils.rejectIfEmptyOrWhitespace(result, "newPwd2", "CANNOTEMPTY");
    if (!result.hasErrors()) {
      if (logedUid == null || logedUid == "") {
        result.reject("UNAUTH");
      } else if (bean.getOldPwd().equals(bean.getNewPwd())) {
        result.rejectValue("newPwd", "CANNOTSAME");
      } else if (!(bean.getNewPwd().equals(bean.getNewPwd2()))) {
        result.rejectValue("newPwd2", "NOTSAME");
      } else if (bean.getNewPwd().length() < 6) {
        result.rejectValue("newPwd", "TOOSIMPLE");
      } else {
        Staff staff = mapper.getByStaffId(logedUid);
        if (staff == null) {
          result.reject("NOTEXISTS");
        } else {
          try {
            String oldPwdHash = DigestAlgorithm.getSHA256().digestHexLowercase(bean.getOldPwd());
            if (!oldPwdHash.equals(staff.getPassword())) {
              result.rejectValue("oldPwd", "NOTMATCH");
            } else {
              String newPwdHash = DigestAlgorithm.getSHA256().digestHexLowercase(bean.getNewPwd());
              mapper.editPassword(logedUid, newPwdHash);
              model.addAttribute("Succeed", true);
            }
          } catch (Exception e) {
            // 不可能
          }
        }
      }
    }
    return "user/editPwd";
  }

  @RequestMapping(value = "/login.do")
  @ResponseBody
  public String login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.authenticate(response);
    return "";
  }

  @RequestMapping(value = "/logout.do")
  public String logout(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    request.logout();
    return "redirect:/";
  }
}
